package vn.team.iwork.calculator;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;

import android.app.Activity;

import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class CalculatorHP15CActivity extends Activity {
	
	private RelativeLayout loRelative;
	
	private ImageView neg;
    private ImageView user;
    private ImageView f;
    private ImageView g;
    private ImageView trigmode;
    private ImageView complex;
    private ImageView prgm;
    private ImageView[] digit;
    private ImageView[] decimal;
    private Map<Character, Bitmap> pixmaps = new HashMap<Character, Bitmap>();
    
    private Context cx;
    private Scriptable scope;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// No title and full screen
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// Landscape mode
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// View
		setContentView(R.layout.main);
		
		final String pixmap_chars = "0123456789";
        for (int i = 0; i < pixmap_chars.length(); i++) {
            char c = pixmap_chars.charAt(i);
            
            //ImageView tmpImg = new ImageView(this);
            InputStream in = null;
    		try {
    			in = getAssets().open("num" + c +".png");
    			Bitmap tmpBm = BitmapFactory.decodeStream(in);
    			pixmaps.put(c, tmpBm);
    			//tmpImg.setImageBitmap(BitmapFactory.decodeStream(in));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }
        
        final String pixmap_chars1 = "abcdeoru";
        for (int i = 0; i < pixmap_chars1.length(); i++) {
        	char c = pixmap_chars1.charAt(i);
        	InputStream in = null;
    		try {
    			in = getAssets().open(c +".png");
    			Bitmap tmpBm = BitmapFactory.decodeStream(in);
    			pixmaps.put(c, tmpBm);
    			//tmpImg.setImageBitmap(BitmapFactory.decodeStream(in));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }
        
        InputStream in = null;
		try {
			in = getAssets().open("decimal.png");
			Bitmap tmpBm = BitmapFactory.decodeStream(in);
			pixmaps.put('.', tmpBm);
			
			in = getAssets().open("comma.png");
			Bitmap tmpBm1 = BitmapFactory.decodeStream(in);
			pixmaps.put(',', tmpBm1);
			//tmpImg.setImageBitmap(BitmapFactory.decodeStream(in));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		loRelative = (RelativeLayout) findViewById(R.id.loRelative);
		
		neg = new ImageView(this);
		neg.setImageResource(R.drawable.neg);
		LayoutParams lopNeg = new LayoutParams(26, 21);
		lopNeg.topMargin = 72;
		lopNeg.leftMargin = 240;
		loRelative.addView(neg, lopNeg);
		
		user = new ImageView(this);
		user.setImageResource(R.drawable.user);
		LayoutParams lopUser = new LayoutParams(11, 26);
		lopUser.topMargin = 100;
		lopUser.leftMargin = 230;
		loRelative.addView(user, lopUser);
		
		f = new ImageView(this);
		f.setImageResource(R.drawable.f);
		LayoutParams lopF = new LayoutParams(11, 6);
		lopF.topMargin = 130;
		lopF.leftMargin = 230;
		loRelative.addView(f, lopF);
		
		g = new ImageView(this);
		g.setImageResource(R.drawable.g);
		LayoutParams lopG = new LayoutParams(11, 7);
		lopG.topMargin = 150;
		lopG.leftMargin = 230;
		loRelative.addView(g, lopG);
		
		complex = new ImageView(this);
		complex.setImageResource(R.drawable.c);
		LayoutParams lopComplex = new LayoutParams(11, 8);
		lopComplex.topMargin = 250;
		lopComplex.leftMargin = 230;
		loRelative.addView(complex, lopComplex);
		
		prgm = new ImageView(this);
		prgm.setImageResource(R.drawable.prgm);
		LayoutParams lopPrgm = new LayoutParams(11, 28);
		lopPrgm.topMargin = 265;
		lopPrgm.leftMargin = 230;
		loRelative.addView(prgm, lopPrgm);
		
		cx = Context.enter();
        scope = cx.initStandardObjects();
        
        /*InputStream inTmp;
		try {
			inTmp = getAssets().open("/matrix.js");
			InputStreamReader tmp = new InputStreamReader(inTmp);
	        
	        cx.evaluateReader(scope, tmp, "/matrix.js", 1, null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
    	
        
        try {
            String[] files = {
                "/sprintf-0.6.js",
                "/matrix.js",
                "/hp15c.js",
                "/test.js",
            };
            for (String fn : files) {
            	InputStream inTmp = getAssets().open(fn);
            	InputStreamReader tmp = new InputStreamReader(inTmp);
                cx.evaluateReader(scope, tmp, fn, 1, null);
            }
        } catch (IOException e) {
        }
        
       /* final String key = cx.evaluateString(scope, String.format("KeyTable[%1$d][%2$d]", 0, 7), null, 1, null).toString();
        Button button7 = (Button) findViewById(R.id.button7);
        button7.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				jsCall("key", key);
			}
		});*/
        
        /*for (int r = 0; r < 4; r++) {
            for (int c = 0; c < 10; c++) {
                Button btn = (findViewById(R.id.b))
                b.setBorderPainted(false);
                b.setPressedIcon(new ImageIcon(face.getImage()) {
                    public void paintIcon(Component c, Graphics g, int x, int y) {
                        g.drawImage(getImage(), 0, 0, 39, h, bx, by+1, bx+39, by+1+h, null);
                    }
                });
                final String key = cx.evaluateString(scope, String.format("KeyTable[%1$d][%2$d]", r, c), null, 1, null).toString();
                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        jsCall("key", key);
                    }
                });
                b.setBounds(bx, by, 39, h);
                pane.add(b, 0);
                if (!(r == 3 && (c == 0 || c == 5))) {
                    String hk = key;
                    if (hk == "\b") {
                        hk = "\u2190";
                    } else if (hk == "\r") {
                        hk = "\u21b2";
                    }
                    JLabel help = new JLabel(hk);
                    help.setBounds(70 + 57 * c, 167 + 65 * r, 16, 16);
                    help.setOpaque(true);
                    help.setBackground(Color.yellow);
                    help.setHorizontalAlignment(SwingConstants.CENTER);
                    help.setFont(new Font("Courier", 0, 14));
                    help.setVisible(false);
                    pane.add(help, 0);
                    helplabels[i] = help;
                }
            }
        }*/
	}
	
	public class Display {
        public void clear_digit(int i) {
        	digit[i].setVisibility(View.INVISIBLE);
        }

        public void clear_digits() {
            for (int i = 0; i < 10; i++) {
            	digit[i].setVisibility(View.INVISIBLE);
            	decimal[i].setVisibility(View.INVISIBLE);
            }
            neg.setVisibility(View.INVISIBLE);
        }

        public void clear_shift() {
            f.setVisibility(View.INVISIBLE);
            g.setVisibility(View.INVISIBLE);
        }

        public void set_comma(int i) {
        	decimal[i].setImageBitmap(pixmaps.get(','));
            decimal[i].setVisibility(View.VISIBLE);
        }

        public void set_complex(int on) {
            complex.setVisibility(on);
        }

        public void set_decimal(int i) {
        	decimal[i].setImageBitmap(pixmaps.get('.'));
            decimal[i].setVisibility(View.VISIBLE);
        }

        public void set_digit(int i, char d) {
        	digit[i].setImageBitmap(pixmaps.get(d));
            digit[i].setVisibility(View.VISIBLE);
        }

        public void set_neg() {
            neg.setVisibility(View.VISIBLE);
        }

        public void set_prgm(int on) {
            prgm.setVisibility(on);
        }

        public void set_shift(String mode) {
            if (mode.equals("f")) {
                f.setVisibility(View.VISIBLE);
            } else if (mode.equals("g")) {
                g.setVisibility(View.VISIBLE);
            }
        }

        /*public void set_trigmode(String mode) {
            if (mode == null) {
                trigmode.setVisibility(View.INVISIBLE);
            } else {
                trigmode.setText(mode);
                trigmode.setVisible(true);
            }
        }*/

        public void set_user(int on) {
            user.setVisibility(on);
        }
    }
	
	void jsCall(String name, Object... args) {
        Function fn = (Function) cx.evaluateString(scope, name, null, 1, null);
        fn.call(cx, scope, null, args);
    }
	
}